from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    # 添加/修改购物车序列化器
    sku_id = serializers.IntegerField(label='商品id')
    count = serializers.IntegerField(label='商品数量')
    selected = serializers.BooleanField(label='勾选状态', default=True)

    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('商品库存不足')
        return attrs

class CartSKUSerializer(serializers.ModelSerializer):
    # 展示购物车序列化器
    count = serializers.IntegerField(label='购物车数量')
    selected = serializers.BooleanField(label='是否勾选')
    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'count', 'default_image_url', 'selected')

class CartDeleteSerializer(serializers.Serializer):
    # 删除购物车序列化器
    sku_id = serializers.IntegerField(label='商品id', min_value=1)
    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        return attrs

class CartSelectedSerializer(serializers.Serializer):
    # 删除购物车序列化器
    selected = serializers.BooleanField(label='全选')
